package a01_数组;

/**
 * <p>
 * a04_长度最小的子数组
 * 滑动窗口
 *   a. 右指针移动到满足条件停止
 *   b. 左指针移动到不满足条件停止
 * </p>
 *
 * @author flyduck
 * @since 2024-06-13
 */
public class a05_长度最小的子数组复习3 {

    public static void main(String[] args) {
//        int[] nums = {2,3,1,2,4,3};
//        int target = 7;
        int[] nums = {2,3,1,2,4,3};
        int target = 7;
        int result = minSubArrayLen(target, nums);
        System.out.println("result = " + result);
    }

    public static int minSubArrayLen(int target, int[] nums) {
        int minLength = Integer.MAX_VALUE;
        int sum = 0;
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            sum = sum + nums[fastIndex];
            while (sum >= target && slowIndex < nums.length) {
                minLength = Math.min(minLength, fastIndex - slowIndex + 1);
                sum = sum - nums[slowIndex];
                slowIndex++;
            }
        }
        if(minLength == Integer.MAX_VALUE){
            return 0;
        }else {
            return minLength;
        }
    }
}
